package com.demo.common.ip2region.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * @Author：DayDayUp
 * @Create：2023/3/13 12:52
 */
public class TempFileUtil {

    public static File loadFile2TempFile(File file) throws IOException {
        InputStream in = Files.newInputStream(file.toPath());
        byte[] buffer = new byte[1024];
        int read = -1;
        File temp;
        FileOutputStream fos = null;
        try {
            temp = File.createTempFile(file.getName(),"");
            temp.deleteOnExit();
            fos = new FileOutputStream(temp);

            while((read = in.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (IOException e) {
            throw new RuntimeException("加载资源包"+ file.getName() +"失败",e);
        }finally {
            try {
                fos.close();
                in.close();
            } catch (IOException e) {
                throw new RuntimeException("关闭流失败",e);
            }
        }
        return temp;
    }

    /**
     * 加载resources文件夹下的资源包到临时目录
     * @param name
     * @return
     */
    public static File loadResource2TempFile(String name) {
        ClassLoader classLoader = TempFileUtil.class.getClassLoader();
        InputStream in = classLoader.getResourceAsStream(name);
        byte[] buffer = new byte[1024];
        int read = -1;
        File temp;
        FileOutputStream fos = null;
        try {
            temp = File.createTempFile(name,"");
            temp.deleteOnExit();
            fos = new FileOutputStream(temp);

            while((read = in.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (IOException e) {
            throw new RuntimeException("加载资源包"+ name +"失败",e);
        }finally {
            try {
                fos.close();
                in.close();
            } catch (IOException e) {
                throw new RuntimeException("关闭流失败",e);
            }
        }
        return temp;
    }

    public static void deleteTempFiles(String name,File tempFile) {
        File[] files = tempFile.getParentFile().listFiles();
        for (File file : files) {
            if (file.getName().startsWith(name)) {
                file.delete();
            }
        }
    }
}
